package com.aat.dxfy.springdata.mongodb.demo2;

import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;
import static org.springframework.data.mongodb.core.query.Update.update;

import java.net.UnknownHostException;
import java.util.List;

import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;

import com.aat.dxfy.springdata.mongodb.demo.Person;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;

public class MongoTest {

	public static void main(String[] args) throws UnknownHostException {
		Mongo mongo = new MongoClient("127.0.0.1", 27017);
		MongoOperations mongoOps = new MongoTemplate(mongo, "test");
		Person p = new Person();
		p.setFirstName("gody");
		p.setLastName("king");

		// add
		mongoOps.insert(p);
		System.out.println("init " + p);

		// delete
		Person pDel = new Person("55da7dcb4d7b3a42c01e4e03");
		mongoOps.remove(pDel);

		// update
		mongoOps.updateFirst(query(where("id").is("55da7e254d7b3a91d0e0b849")), update("lastName", "xingle"),
				Person.class);

		// Find
		Person pFind = mongoOps.findById("55da7e254d7b3a91d0e0b849", Person.class);
		System.out.println("zhao find " + pFind);

		// list
		List<Person> people = mongoOps.findAll(Person.class);
		System.out.println("Number of people = : " + people.size());
		for (Person person : people) {
			System.out.println("person : " + person);
		}

	}

}
